import React, { useEffect, useState } from 'react'
import { PlusOutlined } from '@ant-design/icons'
import {
  Button,
  Col,
  Flex,
  Form,
  Input,
  Row,
  Select,
  Typography,
  Table,
  Alert,
  Switch,
  message
} from 'antd'
import MyDatePicker from '../components/MyDatePicker'
import { Link, useNavigate } from 'react-router-dom'
import {userGroupChangeStatus, userGroupList, userGroupDelete} from '../service/user'
import moment from 'moment'
import { Modal } from 'antd'
export default function UserList() {
  const navigator = useNavigate()
  // 保存选择的日期
  const [selectedDateString, setSelectedDateString] = useState(null)
  // 保存店铺列表
  const [storeList, setStoreList] = useState([])
  // 保存页码
  const [pageNo, setPageNo] = useState(1)
  // 总数据量
  const [total, setTotal] = useState(0)
  // 预设日期
  // 保存表格中选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 表格中是否有选中
  const hasSelected = selectedRowKeys.length > 0
  // 搜索条件
  const [condition, setCondition] = useState({})
  // 用于更新列表
  const [n, setN] = useState(1)
  const request = async () => {
    const res = await userGroupList({
      ...condition,
      pageNo,
      pageSize: 10
    })
    console.log(res)
    if (res.data) {
      setStoreList(res.data.objects)
      setTotal(res.data.total)
    }
  }
  const handleDelete = (id, groupName) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除人群「${groupName}」吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await userGroupDelete(id)
          message.success('删除成功')
          setN(n + 1) // 刷新列表
        } catch (error) {
          message.error('删除失败')
          console.error('删除失败:', error)
        }
      }
    })
  }
  useEffect(() => {
    request()
  }, [n, pageNo])

  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'}>
            <Typography.Title level={3}>信息管理</Typography.Title>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigator('/admin/user/addCrowd')}
            >
              新建人群
            </Button>
          </Flex>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Form
            layout="inline"
            onFinish={async (values) => {
              setCondition(values)
              console.log(values)
              await request()
              setN(n + 1)
            }}
          >
            <Form.Item label="人群名称：" name="groupName">
              <Input placeholder="请输入人群名称" />
            </Form.Item>
            <Form.Item label="发布状态：" name="providerType">
              <Select
                style={{ width: 200 }}
                placeholder="选择发布状态"
                options={[
                  {
                    value: '',
                    label: '全部'
                  },
                  {
                    value: '0',
                    label: 'APP'
                  },
                  {
                    value: '1',
                    label: '小程序'
                  },
                  {
                    value: '2',
                    label: '支付宝生活号'
                  }
                ]}
              />
            </Form.Item>

            <Form.Item label="创建时间">
              <MyDatePicker
                selectedDateString={selectedDateString}
                setSelectedDateString={setSelectedDateString}
              />
            </Form.Item>

            <Form.Item>
              <Button type="default" htmlType="reset">
                重置
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Typography.Paragraph style={{ fontSize: 16 }}>
            人群列表
          </Typography.Paragraph>
          {hasSelected && (
            <Alert
              message={`已经选择 ${selectedRowKeys.length} 项`}
              type="info"
              showIcon
            />
          )}
        </Col>
        <Col span={24}>
          <Table
            pagination={{
              total,
              defaultCurrent: 1,
              onChange: async (page) => {
                setPageNo(page)
              }
            }}
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (newSelectedRowKeys) => {
                console.log('selectedRowKeys changed: ', newSelectedRowKeys)
                setSelectedRowKeys(newSelectedRowKeys)
              }
            }}
            dataSource={storeList}
            columns={[
              {
                title: '编号',
                dataIndex: 'id',
                key: 'id'
              },
              {
                title: '人群名称',
                dataIndex: 'groupName',
                key: 'groupName'
              },
              {
                title: '用户数量',
                dataIndex: 'userNumber',
                key: 'userNumber',
                render: (text, record) => {
                  return <>查看（{record.userNumber}）</>
                }
              },
              {
                title: '活动数量',
                dataIndex: 'activeCount',
                key: 'activeCount',
                render: (_, record) => {
                  return <>查看（5）</>
                }
              },
              {
                title: '人群介绍',
                dataIndex: 'groupDescription;',
                key: 'groupDescription;',
                render: (_, record) => {
                  return <>（{record.groupDescription}）</>
                }
              },
              {
                title: '创建时间',
                dataIndex: 'createAt',
                key: 'createAt',
                render: (text, record) => {
                  const storedCreateTime = localStorage.getItem(`crowd_${record.id}_createTime`);
                  if (storedCreateTime) {
                    return storedCreateTime;
                  } else {
                    // 假设record.createAt是时间戳格式，需要使用moment格式化
                    const originalCreateTime = moment(record.createAt).format('YYYY-MM-DD HH:mm:ss');
                    localStorage.setItem(`crowd_${record.id}_createTime`, originalCreateTime);
                    return originalCreateTime;
                  }
                }
              },
              {
                title: '启动状态',
                dataIndex: 'status',
                key: 'status',
                render: (text, record) => {
                  return <Switch
                    checked={record.status === 1}
                    onChange={async (checked) => {
                      try {
                        // 调用状态变更接口
                        await userGroupChangeStatus({
                          id: record.id,
                          status: checked ? 1 : 0 // 根据开关状态设置新状态值
                        })
                        // 状态更新成功后可以刷新数据或直接更新本地状态
                        message.success('状态更新成功')
                        // 这里可以调用刷新列表的函数
                        // loadData()
                        setN(n + 1)
                      } catch (error) {
                        message.error('状态更新失败')
                        console.error('状态更新失败:', error)
                      }
                    }}
                  />
                }
              },
              {
                title: '操作',
                dataIndex: 'op',
                key: 'op',
                align: 'center',
                render: (_, record) => {
                  return (
                      <span className="op">
                      <Link to={`/admin/user/editCrowd/${record.id}`}>
                        编辑
                      </Link>
                       <a style={{marginLeft: 10}} onClick={() => handleDelete(record.id, record.groupName)}>删除</a>
                    </span>
                )
                }
                }
                ]}
                />
                </Col>
      </Row>
    </>
  )
}
